import React from 'react';
import { Routes, Route, Navigate } from 'react-router-dom';
import { useAuth } from './context/AuthContext';

// 页面组件
import Login from './pages/Login';
import Dashboard from './pages/Dashboard';
import SourcesList from './pages/SourcesList';
import SourceDetail from './pages/SourceDetail';
import PersonnelList from './pages/PersonnelList';
import PersonnelDetail from './pages/PersonnelDetail';
import ChangelogList from './pages/ChangelogList';
import UserManagement from './pages/UserManagement';
import NotFound from './pages/NotFound';

// 布局组件
import Layout from './components/Layout';

// 私有路由组件 - 用于保护需要登录的路由
const PrivateRoute = ({ children }) => {
  const { isAuthenticated, loading } = useAuth();
  
  if (loading) {
    return <div className="loading">加载中...</div>;
  }
  
  return isAuthenticated ? children : <Navigate to="/login" />;
};

// 管理员路由组件 - 用于保护需要管理员权限的路由
const AdminRoute = ({ children }) => {
  const { isAuthenticated, user, loading } = useAuth();
  
  if (loading) {
    return <div className="loading">加载中...</div>;
  }
  
  return isAuthenticated && user?.role === 'admin' ? 
    children : 
    <Navigate to="/dashboard" />;
};

function App() {
  return (
    <Routes>
      <Route path="/login" element={<Login />} />
      
      <Route path="/" element={
        <PrivateRoute>
          <Layout />
        </PrivateRoute>
      }>
        <Route index element={<Navigate to="/dashboard" />} />
        <Route path="dashboard" element={<Dashboard />} />
        
        <Route path="sources">
          <Route index element={<SourcesList />} />
          <Route path=":id" element={<SourceDetail />} />
        </Route>
        
        <Route path="personnel">
          <Route index element={<PersonnelList />} />
          <Route path=":id" element={<PersonnelDetail />} />
        </Route>
        
        <Route path="changelog" element={<ChangelogList />} />
        
        <Route path="users" element={
          <AdminRoute>
            <UserManagement />
          </AdminRoute>
        } />
      </Route>
      
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
}

export default App; 